﻿using System;
using EmbeddedSharp.Core;
using Zove.Runtime.Core;

namespace Zove.Scripting.Core
{
    /// <summary>
    /// ZoveScript unary function
    /// </summary>
    public class ZoveScriptingUnaryFunctionTranslator :
        UnaryFunctionTranslator
    {
        public ZoveScriptingUnaryFunctionTranslator(
            IFunctionManager funMgr, string subject)
            : base(funMgr, subject)
        {
        }

        public IZoveScriptingContext Context { get; set; }

        public override object Visit(IdentifierNode node)
        {
            RuntimeFactor factor = Context.GetFactor(node.Value);

            string name = string.Empty;
            if (factor == null)
            {
                name = node.Value;
            }
            else if (factor.Model != null
                     && factor.Model.Instance.Name != null)
            {
                name = factor.Model.Instance.Name
                       + "." + factor.Name;
            }
            if (base.subject == name)
            {
                return "x";
            }

            if (factor.Status != RuntimeFactorStatus.Unknown)
            {
                return factor.Value;
            }

            throw new Exception(
                string.Format(
                    "Factor {0} must be specified.", factor.Name));
        }
    }
}